package com.itheima;

import com.itheima.pojo.Employee;
import org.springframework.beans.BeanUtils;

import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;

/**
 * @version 1.0
 * @description 说明
 * @package com.itheima
 */
public class ReflectionDemo {
    public static void main(String[] args) throws Exception {
        String clsName = "com.itheima.pojo.Employee";
        // 要求创建一个employee对象，且
        Class<?> cls = Class.forName(clsName);// 通过字符串获取类的字节码：描述这个类下有哪些属性与方法
        //Employee employee = new Employee();
        Object o = cls.newInstance();//创建一个对象, 调用无参构造方法
        System.out.println(o);
        // 设置它的name=张三,
        // 获取employee对象的name的值
        // 获取类中的所有属性
        Field[] fields = cls.getDeclaredFields();
        for (Field field : fields) {
            System.out.println(field.getName());
        }
        // 遍历
        Method[] declaredMethods = cls.getDeclaredMethods();
        for (Method method : declaredMethods) {
            System.out.println(method.getName());
        }
        // 设置username=zs
        // 通过属性设置
        Field usernameField = cls.getDeclaredField("username");
        // 暴力
        usernameField.setAccessible(true);
        usernameField.set(o,"zs");
        System.out.println(usernameField.get(o));
        // 通过set方法设置
        Method setUsername = cls.getDeclaredMethod("setUsername", String.class);
        setUsername.invoke(o,"zhangsan");
        Method getUsername = cls.getDeclaredMethod("getUsername");
        Object value = getUsername.invoke(o);
        System.out.println("getUsername=" + value);

        // 获取 employee对象的username的值
        // 属性的描述, 就有getter与setter方法
        PropertyDescriptor nameDescriptor = BeanUtils.getPropertyDescriptor(cls, "name");
        // 获取get方法
        Method getMethod = nameDescriptor.getReadMethod();
        System.out.println("getMethod = " + getMethod.getName());
        Method setMethod = nameDescriptor.getWriteMethod();
        System.out.println("setMethod = " + setMethod.getName());

        setMethod.invoke(o,"张三");
        Object nameValue = getMethod.invoke(o);
        System.out.println("nameValue = " + nameValue);
    }
}
